package com.culturalCenter.dataCenter.globalconfig.security;


import com.culturalCenter.dataCenter.globalconfig.filter.*;
import com.culturalCenter.dataCenter.mapper.sysauth.SystemAuthMapper;
import com.culturalCenter.dataCenter.service.impl.UserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;


/**
 * 安全配置：
 *
 * @author : wulincheng
 * @date : 13:40 2020/6/9
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)// 启用方法级的权限认证
@EnableWebSecurity
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.head}")
    private String head;
    @Value("${userAscii_key}")
    private String userAsciiKey;
    @Value("${checkToken}")
    private Boolean checkToken;
    /**
     * 获取授权放行路径
     */
    @Value("${jwt.permitUris}")
    private String permitUris;
    /**
     * 检查权限
     */
    @Value("${checkAuthority}")
    private Boolean checkAuthority;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 自定义决策管理器
     */
    @Resource
    private CustomAccessDecisionManager customAccessDecisionManager;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private SystemAuthMapper systemAuthMapper;
    @Value("${token.host}")
    private String tokenHostUrl;
    @Value("${token.checkToken}")
    private String checkTokenUrl;

    /**
     * 数据库中取出用户信息
     */
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }

    /**
     * HTTP请求安全处理
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        String[] urlArray;
        if (!checkAuthority) {
            permitUris = permitUris.concat(",/**");
        }
        urlArray = permitUris.split(",");

        http.authorizeRequests()
                .antMatchers(urlArray).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and().exceptionHandling().authenticationEntryPoint(new RestAuthenticationEntryPoint())
                // 处理用户登录后的无权访问
                .accessDeniedHandler(new AccessDenied())
                .and()
                .addFilter(new LoginAuthenticationFilter(authenticationManager(), head, tokenHeader, userAsciiKey, redisTemplate))
                .addFilter(new AuthenticateFilter(authenticationManager(), tokenHeader, head, userDetailsService(), permitUris, userAsciiKey, redisTemplate, checkToken, tokenHostUrl, checkTokenUrl, restTemplate, systemAuthMapper))
                .csrf().disable()
                .httpBasic()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.cors();
        // 将自定义的过滤器配置在FilterSecurityInterceptor之前
        http.addFilterBefore(customFilterSecurityInterceptor(), FilterSecurityInterceptor.class);
        http.addFilterBefore(customHeaderFilter(), AuthenticateFilter.class);
    }

    /**
     * 管理自定义的权限过滤器
     */
    @Bean
    public CustomFilterSecurityInterceptor customFilterSecurityInterceptor() {
        CustomFilterSecurityInterceptor fi = new CustomFilterSecurityInterceptor();
        fi.setMyAccessDecisionManager(customAccessDecisionManager);
        return fi;
    }

    /**
     * 管理自定义的请求头过滤器
     */
    @Bean
    public CustomHeaderFilter customHeaderFilter() {
        return new CustomHeaderFilter();
    }

    /**
     * WEB安全
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/swagger-ui.html")
//                .antMatchers("/v2/api-docs")
                .antMatchers("/swagger-resources/**")
                .antMatchers("/webjars/**")
                .antMatchers("/doc.html")
                .antMatchers("/v1/activity/informationScreen")
                .antMatchers("/v1/activity/informationScreen/site")
                .antMatchers("/v1/activity/informationScreen/status")
                .antMatchers("/v1/activity/smartDisplay")
                .antMatchers("/v1/activity/navigationScreen")
                .antMatchers("/v1/passengerflow/**")
                .antMatchers("/v1/weather/getWeather")
                .antMatchers("/v1/sms/sendMsg")
                .antMatchers("/v1/monitor/**")
                .antMatchers("/v1/user/analysis")
                .antMatchers("/v1/equipData/**")
                .antMatchers("/v1/training/table")
                .antMatchers("/v1/training/resourceDistributionTable")
                .antMatchers("/v1/training/latestResourceRecommend")
                .antMatchers("/v1/wechat/**")
        // .antMatchers("/error")
        ;
        super.configure(web);
    }

    /**
     * 认证管理器
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 身份验证管理生成器
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
        // 使用自定义的授权认证
        // auth.authenticationProvider(new AuthProvider(userDetailsService(), passwordEncoder()));
    }

    /**
     * 干掉默认的授权前缀
     * 工作方式.access("hasRole('USER')")而不是 hasRole('USER')
     */
    @Bean
    GrantedAuthorityDefaults grantedAuthorityDefaults() {
        // Remove the ROLE_ prefix
        return new GrantedAuthorityDefaults("");
    }

    /**
     * spring security 5.0之后加密格式改变了，SecurityConfig类中加入
     * //      return new BCryptPasswordEncoder();
     */
    @Bean
    BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 解决跨域问题
     */
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

}
